package com.autonavi.yunda.yunji.common.utils.http;

import com.google.common.collect.Maps;
import org.apache.logging.log4j.util.Strings;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author cizhong.wcs
 * @date 2022/1/29 6:46 下午
 */
public class RequestParser {
    public static final String HEADER_X_REAL_IP = "x-real-ip";
    public static final String HEADER_X_FORWARDED_FOR = "x-forwarded-for";
    public static final String HEADER_PROXY_CLIENT_IP = "proxy-client-ip";
    public static final String HEADER_WL_PROXY_CLIENT_IP = "wl-proxy-client-ip";
    public static final String HEADER_HTTP_CLIENT_IP = "http_client_ip";
    public static final String HEADER_HTTP_X_FORWARDED_FOR = "http_x_forwarded_for";
    public static final String UNKNOWN = "unknown";

    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headers = Maps.newHashMap();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (null != headerNames) {
            while (headerNames.hasMoreElements()) {
                String headerKey = headerNames.nextElement();
                String headerValue = request.getHeader(headerKey);
                headers.put(headerKey, headerValue);
            }
        }
        return headers;
    }

    public static String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader(HEADER_X_FORWARDED_FOR);
        if (Strings.isNotBlank(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
            int index = ip.indexOf(",");
            if (index > 0) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader(HEADER_WL_PROXY_CLIENT_IP);
        if (Strings.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER_PROXY_CLIENT_IP);
        }
        if (Strings.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER_HTTP_CLIENT_IP);
        }
        if (Strings.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER_HTTP_X_FORWARDED_FOR);
        }
        if (Strings.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER_X_REAL_IP);
        }
        if (Strings.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (Strings.isBlank(ip)) {
            return "";
        }
        int i = ip.indexOf(",");
        if (i > 0) {
            return ip.substring(0, i);
        }
        return ip;
    }

}
